const _ = require('lodash');
const qs = require('qs');
const Promise = require('bluebird');
const moment = require("moment");
const axios = require('axios');
const Handlebars = require('handlebars');

module.exports = function (storage, config, cookiesInstance) {
  let {modelsData: {Goodses}, models: {EventApplies, EventFails, JDEventApplies, JDEventFails, Users, AgencysCoupons, ShortUrls}, search: {searchEnable, goodsesSearch}, utils, taobaoApi} = storage, {captureHosts, webservice_key, pid, applyreason, domain} = config;

  let we_template = Handlebars.compile(`【商品】{{title}}\n{{#if quan_amount}}领{{quan_amount}}元券，券后【{{quan_price}}元】{{^}}价格: 【{{price}}元】{{/if}}\n{{#if intro}}【推荐理由】{{intro}}\n{{/if}}{{#if goodsUrl}}【商品链接】{{{goodsUrl}}}\n{{/if}}{{#if domain}}【更多优惠券】{{{domain}}}\n{{/if}}【口令】{{tkl}}\n复制这条信息，打开☞手机淘宝☜即可查看并下单！`);
  let buy_template = Handlebars.compile(`【商品】{{title}}\n{{#if quan_amount}}领{{quan_amount}}元券，券后【{{quan_price}}元】{{^}}价格: 【{{price}}元】{{/if}}\n{{#if goodsUrl}}【商品链接】{{goodsUrl}}\n{{/if}}{{#if domain}}【更多优惠券】{{{domain}}}\n{{/if}}【口令】{{tkl}}\n复制这条信息，打开☞手机淘宝☜即可查看并下单！`);

  /**
   * 获取分享链接
   */
  let getShareUrl = function ({goods, agency}) {
    let activityId = goods.activityId;
    let itemId = goods.auctionId;
    let agencyPid = agency.pid || pid;
    let returnUlandUrl = function () {
      return Promise.resolve({
        shareUrl: 'https://uland.taobao.com/coupon/edetail?activityId=' + activityId + '&pid=' + agencyPid + '&itemId=' + itemId + '&src=pylsite&dx=1' + (goods && goods.commissionType == 'MKT' ? '&mt=1' : '')
      });
    }
    if (activityId) {
      return returnUlandUrl();
    }
    return AgencysCoupons.findOne({
      where: {agency_pid: agencyPid, goods_id: itemId},
      attributes: ['id', 'couponLink']
    }).then(function (agencysCoupon) {
      if (agencysCoupon) {
        let shareUrl = 'https://uland.taobao.com/coupon/edetail?e=' + agencysCoupon.couponLink + '&pid=' + agencyPid + '&src=pylsite&af=1' + (goods && goods.commissionType == 'MKT' ? '&mt=1' : '');
        return taobaoApi.getTkl({
          url: shareUrl,
          logo: goods.pictUrl,
          text: goods.title
        }).then(function (result) {
          let couponTkl = result && result.model || '';
          if (!couponTkl) {
            console.error('第一次获取淘口令失败');
            return taobaoApi.getTkl({
              url: shareUrl,
              logo: goods.pictUrl,
              text: goods.title
            }).then(function (result) {
              let couponTkl = result && result.model || '';
              if (!couponTkl) {
                console.error('第二次获取淘口令失败');
              }
              return {
                shareUrl: shareUrl,
                couponTkl: couponTkl
              }
            });
          }
          return {
            shareUrl: shareUrl,
            couponTkl: couponTkl
          }
        });
      }

      return cookiesInstance.getInstance({
        domain: 'alimama.com',
        username: agency.tao_user
      }).then(function ({instance, cookie}) {
        if (!instance) {
          return returnUlandUrl();
        }
        let arr = agencyPid.split('_');
        let tkarr = cookie.cookies.match("_tb_token_\=(.*?);");
        let _tb_token_ = tkarr && tkarr[1] || '';
        let siteid = arr[2];
        let adzoneid = arr[3];
        return instance.get('http://pub.alimama.com/common/code/getAuctionCode.json?auctionid=' + itemId + '&adzoneid=' + adzoneid + '&siteid=' + siteid + '&scenes=1&_tb_token_=' + _tb_token_).then(function (response) {
          let result = response.data;
          if (result && result.ok) {
            let data = result.data;
            if (data.couponLink) {
              let e = utils.getQueryString(data.couponLink, 'e');
              AgencysCoupons.create({
                agency_id: agency.id,
                agency_pid: agencyPid,
                goods_id: itemId,
                couponLink: e
              });
              return {
                shareUrl: data.couponLink,
                couponTkl: data.couponLinkTaoToken
              };
            }
            return {
              shareUrl: data.clickUrl
            };
          }
          return returnUlandUrl();
        });
      });
    });
  }

  /**
   * 申请高佣
   */
  let applyCampaign = function ({goods, agency}) {
    if (!(agency && agency.tao_user) || goods.commissionType != 'SP') {
      return;
    }
    return cookiesInstance.getInstance({
      domain: 'alimama.com',
      username: agency.tao_user
    }).then(function ({instance, cookie}) {
      if (!instance) {
        return;
      }
      let apply = function (data) {
        return EventApplies.findOne({
          where: {
            tao_user: agency.tao_user,
            goods_id: goods.auctionId,
            CampaignID: goods.eventCampId
          }
        }).then(function (eventApply) {
          if (!eventApply) {
            return instance.post('http://pub.alimama.com/pubauc/applyForCommonCampaign.json', qs.stringify(data)).then(function (response) {
              let result = response.data;
              if (result.ok || (result.info && result.info.message && result.info.message.indexOf('您已经在申请该计划') != -1)) {
                return EventApplies.create({
                  tao_user: agency.tao_user,
                  goods_id: goods.auctionId,

                  CampaignID: data.campId,
                  ShopKeeperID: data.keeperid
                });
              } else {
                return EventFails.create({
                  tao_user: agency.tao_user,
                  goods_id: goods.auctionId,

                  ext_data: JSON.stringify({
                    data: data,
                    result: result
                  })
                });
              }
            });
          }
        });
      }

      if (goods.eventCampId && goods.eventKeeperid) {
        let tkarr = cookie.cookies.match("_tb_token_\=(.*?);");
        let _tb_token_ = tkarr && tkarr[1] || '';

        return apply({
          campId: goods.eventCampId,
          keeperid: goods.eventKeeperid,
          applyreason: applyreason,
          _tb_token_: _tb_token_
        });
      }
      return instance.get('http://pub.alimama.com/pubauc/getCommonCampaignByItemId.json?itemId=' + goods.auctionId).then(function (response) {
        let list = response.data && response.data.data;
        let max = null;
        if (list && list.length) {
          for (let i in list) {
            let item = list[i];
            if (!item.manualAudit) {
              if (!max || max.commissionRate < item.commissionRate) {
                max = item;
              }
            }
          }
        }
        return max;
      }).then(function (max) {
        if (!max) {
          return;
        }
        if (goods.tkRate >= max.commissionRate) {
          console.log('能用佣金大于或等于定向');
          return;
        }
        Goodses.update({
          eventCampId: max.CampaignID,
          eventKeeperid: max.ShopKeeperID,
          eventRate: max.commissionRate,
          eventFee: (goods.zkPrice * max.commissionRate / 100).toFixed(2)
        }, {where: {id: goods.id}});

        let tkarr = cookie.cookies.match("_tb_token_\=(.*?);");
        let _tb_token_ = tkarr && tkarr[1] || '';
        return apply({
          campId: max.CampaignID,
          keeperid: max.ShopKeeperID,
          applyreason: applyreason,
          _tb_token_: _tb_token_
        });
      });
    });
  }

  /**
   * 获取分享文本
   */
  let getShareText = function ({goods, user, agency}) {
    return getShareUrl({goods, agency}).then(function ({shareUrl, couponTkl}) {
      return Promise.props({
        tkl: couponTkl || taobaoApi.getTkl({
          url: shareUrl,
          logo: goods.pictUrl,
          text: goods.title
        }).then(function (result) {
          let couponTkl = result && result.model || '';
          if (couponTkl) {
            return couponTkl;
          }
          console.log('第一次获取淘口令失败');
          return taobaoApi.getTkl({
            url: shareUrl,
            logo: goods.pictUrl,
            text: goods.title
          }).then(function (result) {
            let couponTkl = result && result.model || '';
            if (!couponTkl) {
              console.log('第二次获取淘口令失败');
            }
            return couponTkl;
          });
        })
      }).then(function ({tkl}) {
        let data = {
          title: goods.title,
          price: goods.zkPrice,
          quan_amount: goods.couponAmount,
          quan_price: goods.quanPrice,
          intro: goods.intro,
          tkl: tkl,
          goodsUrl: domain + '/detail?id=' + goods.auctionId + ((user && user.id) ? ('&inviter_id=' + user.id) : ''),
          domain: domain + ((user && user.id) ? ('?inviter_id=' + user.id) : '')
        };
        return we_template(data);
      });
    });
  }

  /**
   * 获取购买文本
   */
  let getBuyKouling = function ({goods, user, agency}) {
    return getShareUrl({goods, agency}).then(function ({shareUrl, couponTkl}) {
      return Promise.props({
        tkl: couponTkl || taobaoApi.getTkl({
          url: shareUrl,
          logo: goods.pictUrl,
          text: goods.title
        }).then(function (result) {
          let couponTkl = result && result.model || '';
          if (couponTkl) {
            return couponTkl;
          }
          console.log('第一次获取淘口令失败');
          return taobaoApi.getTkl({
            url: shareUrl,
            logo: goods.pictUrl,
            text: goods.title
          }).then(function (result) {
            let couponTkl = result && result.model || '';
            if (!couponTkl) {
              console.log('第二次获取淘口令失败');
            }
            return couponTkl;
          });
        })
      }).then(function ({tkl}) {
        let data = {
          title: goods.title,
          price: goods.zkPrice,
          quan_amount: goods.couponAmount,
          quan_price: goods.quanPrice,
          intro: goods.intro,
          tkl: tkl,
          goodsUrl: domain + '/detail?id=' + goods.auctionId + ((user && user.id) ? ('&inviter_id=' + user.id) : ''),
          domain: domain + ((user && user.id) ? ('?inviter_id=' + user.id) : '')
        };
        return buy_template(data);
      });
    });
  }

  /**
   * 处理分享
   */
  let handleShare = function ({goods, openid}) {
    return Users.findOne({where: {openid: openid}}).then(function (user) {
      if (user && user.tao_user) {
        return {
          user: user,
          agency: user
        };
      }
      return Users.findOne({where: {id: user && user.agency_id || 1}}).then(function (agency) {
        return {
          user: user,
          agency: agency
        };
      });
    }).then(function ({user, agency}) {
      return getShareText({
        goods: goods,
        user: user,
        agency: agency
      }).then(function (text) {
        return {
          success: true,
          goods: goods,
          text: text,
          user: user,
          agency: agency
        };
      });
    });
  }

  let getGoodsByAuctionId = function ({id, title, user_id}) {

    return Goodses.findOne({where: {auctionId: id}}).then(function (goods) {
      if (goods && goods.zkPrice && goods.title) {
        return goods;
      }
      if (goods) {
        Goodses.destroy({where: {id: goods.id}}).then(function () {
          console.log('删除商品', goods.id, id);
        });
      }
      let body = {url: 'https://detail.tmall.com/item.htm?id=' + id}, method = 'findOne';
      let captureRquest = async function (action) {
        // let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
        // return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, body).then(function (response) {
        //   return response.data;
        // }).catch(function (err) {
        //   if (err) {
        //     console.error('\n', err.stack || err.message);
        //   }
        //   return {success: false};
        // });
        return {success: false};
      };
      return Promise.props({
        qingtaoke: captureRquest('qingtaoke'),
        yishoudan: captureRquest('yishoudan'),
        taokezhushou: captureRquest('taokezhushou'),
        dataoke: captureRquest('dataoke')
      }).then(function (result) {
        for (let i in result) {
          let item = result[i];
          if (item.success && item.data) {
            item.data.source = i + '_' + (user_id || '');
            return Goodses.create(item.data);
          }
        }
        return Goodses.create({auctionId: id, title: title, source: 'share_' + (user_id || '')});
      }).then(function (pendingGoods) {
        return taobaoApi.getGoods(pendingGoods.auctionId).then(function (goods) {
          if (goods) {
            delete goods.activityId;
            return Goodses.update(goods, {where: {id: pendingGoods.id}}).then(function () {
              return goods;
            });
          }
          return goods;
        }).then(function (goods) {
          if (goods && goods.title || pendingGoods.title) {
            return taobaoApi.getMaterial(pendingGoods.auctionId, goods && goods.title || pendingGoods.title).then(function (material) {
              if (material) {
                return Goodses.update(material, {where: {id: pendingGoods.id}}).then(function () {
                  return material;
                });
              }
              return material;
            });
          }
        }).then(function (material) {
          if (material && material.activityId || pendingGoods.activityId) {
            return taobaoApi.getCoupon(pendingGoods.auctionId, material && material.activityId || pendingGoods.activityId).then(function (coupon) {
              if (coupon) {
                return Goodses.update(coupon, {where: {id: pendingGoods.id}});
              }
            });
          }
        }).then(function () {
          return Goodses.findOne({where: {id: pendingGoods.id}}).then(function (goods) {
            if (!goods.zkPrice || !goods.title) {
              return Goodses.update({status: 'Deactivated'}, {where: {id: pendingGoods.id}}).then(function () {
                goods.status = 'Deactivated';
                return goods;
              });
            }
            let data = {
              quanPrice: (goods.zkPrice - (goods.couponAmount || 0)).toFixed(2),
              status: 'Active'
            }
            if (data.quanPrice <= 3) {
              data.is30 = 1;
            }
            if (data.quanPrice <= 10) {
              data.is99 = 1;
            }
            if (data.quanPrice <= 20) {
              data.is199 = 1;
            }
            for (let i in data) {
              goods[i] = data[i];
            }
            return Goodses.update(data, {where: {id: pendingGoods.id}}).then(function () {
              if (searchEnable) {
                goodsesSearch.index(goods);
              }
              return goods;
            });
          });
        }).catch(function (err) {
          if (err) {
            console.error('\n', err.stack || err.message);
          }
          return {};
        });
      });
    });
  }

  let getGoodsByUrl = function ({url, title, user_id}) {
    return utils.getRealUrl(url).then(function (realUrl) {
      if (!realUrl) {
        return {success: false, message: 'url无效:' + url};
      }
      let id = utils.getQueryString(realUrl, 'id');
      return getGoodsByAuctionId({id: id, title: title, user_id: user_id}).then(function (goods) {
        if (!goods) {
          return {success: false, message: '获取商品失败'};
        }
        return {success: true, data: goods};
      });
    });
  }


  /**
   * 价格走势
   */
  let priceTrend = function ({url}) {
    let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
    let action = 'huihui', method = 'priceTrend';
    return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, {
      url: url
    }).then(function (response) {
      return response.data;
    }).catch(function (err) {
      if (err) {
        console.error('\n', err.stack || err.message);
      }
      return {success: false};
    });
  }

  /**
   * 计算返利金額
   */
  let getUserFanli = function ({fee, agency}) {
    return (fee * agency.order_return_scale / 100).toFixed(2);
  }

  /**
   * 计算代理佣金
   */
  let getAgencyIncome = function ({fee, agency}) {
    return (fee * agency.agency_scale / 100).toFixed(2);
  }

  /**
   * 阿里妈妈搜索
   */
  let alimamaSearch = function ({title, pageSize}) {
    let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
    let action = 'alimama', method = 'findByTitle';
    return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, {
      title: title,
      pageSize: pageSize
    }).then(function (response) {
      return response.data;
    }).catch(function (err) {
      if (err) {
        console.error('\n', err.stack || err.message);
      }
      return {success: false};
    });
  }

  let alimamaAdzones = function (agency) {
    return cookiesInstance.getInstance({
      domain: 'alimama.com',
      username: agency.tao_user
    }).then(function ({instance, cookie}) {
      if (!instance) {
        console.error('alimama.com 获取可用账户失败');
        return {success: false, message: '获取可用账户失败'};
      }
      return instance.get('https://pub.alimama.com/common/adzone/newSelfAdzone2.json?tag=29').then(function (response) {
        let adzones = [];
        if (response.data && response.data.data && response.data.data.otherAdzones) {
          let otherAdzones = response.data.data.otherAdzones;
          for (let i in otherAdzones) {
            let otherAd = otherAdzones[i];
            adzones.push({
              value: otherAd.id,
              text: otherAd.name
            })
          }
        } else {
          console.error('newSelfAdzone2', response.data);
        }
        return {success: true, data: adzones};
      });
    });
  }

  let alimamaAdzoneCreate = function (agency, body) {
    if (!body.siteid || !body.newadzonename) {
      return {success: false, message: '参数错误'};
    }
    return cookiesInstance.getInstance({
      domain: 'alimama.com',
      username: agency.tao_user
    }).then(function ({instance, cookie}) {
      if (!instance) {
        return {success: false, message: '获取可用账户失败'};
      }
      let tkarr = cookie.cookies.match("_tb_token_\=(.*?);");
      let _tb_token_ = tkarr && tkarr[1] || '';
      return instance.post('https://pub.alimama.com/common/adzone/selfAdzoneCreate.json', qs.stringify({
        tag: 29,
        gcid: 8,
        selectact: 'add',
        siteid: body.siteid,
        newadzonename: body.newadzonename,
        t: new Date().getTime(),
        _tb_token_: _tb_token_
      })).then(function (response) {
        if (response.data && response.data.ok) {
          return {
            success: true,
            data: response.data.data
          };
        }
        return {success: false};
      });
    });
  }

  /**
   * 短链接
   */
  let getShortUrl = function (shareUrl) {
    return ShortUrls.findOne({where: {url: shareUrl}}).then(function (url) {
      if (url) {
        return config.domain + '/' + url.id;
      }
      return ShortUrls.create({url: shareUrl}).then(function (url) {
        return config.domain + '/' + url.id;
      });
    }, function () {
      return shareUrl;
    });
  }

  /**
   * 京东
   */
  let getJdGoodsById = function ({id}) {
    return JDGoodses.findOne({where: {skuId: id}}).then(function (goods) {
      if (goods) {
        return goods;
      }
      let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
      return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=jd&method=findOne', {id: id}).then(function (response) {
        let result = response.data;
        if (result.success && result.data) {
          let data = result.data;
          JDGoodses.create(data);
          return data;
        }
      }).catch(function (err) {
        if (err) {
          console.error('\n', err.stack || err.message);
        }
      });
    });
  }

  let jdApplyEvent = function (goods, agency) {
    return JDEventApplies.findOne({
      where: {
        jd_user: agency.jd_user,
        jd_pid: agency.jd_pid,
        goods_id: goods.skuId
      }
    }).then(function (event) {
      if (event) {
        return event;
      }
      return cookiesInstance.getInstance({
        username: agency.jd_user,
        domain: 'media.jd.com'
      }).then(function ({instance, cookie}) {
        if (!instance) {
          return;
        }
        return instance.post('https://media.jd.com/gotoadv/getCustomCode/1', qs.stringify({
          logType: 0,
          logPromotionType: 1,
          logTitle: goods.skuName,
          logUnitPrice: goods.wlPrice,
          logSaler: 1,
          logCommissionLock: 0,
          logPromotionStartTime: '2017-09-01',
          logPromotionEndTIme: '2999-01-01',
          imgUrl: 'http://img14.360buyimg.com/n1/' + goods.imageUrl,
          logCommissionRate: goods.wlCommissionShare,
          logHotKey: goods.venderName || '--',
          materialType: 1,
          materialId: goods.skuId,
          positionId: agency.jd_pid,
          sizeType: 2,
          height: 0,
          width: 0,
          wareUrl: 'http://item.jd.com/' + goods.skuId + '.html',
          adOwner: goods.adowner,
          planId: goods.planId || 0,
          CPType: 'CPS',
          cacheType: '02_gotoadv',
          receiveCodeType: 1,
          landingPageType: 0,
          adtType: 31,
          protocol: 2,
          unionAppId: -1,
          unionMediaId: -1,
          unionWebId: -1,
          landingType: 0,
          codeType: 1,
          type: 1,
          spaceName: agency.jd_pid,
          sizeId: -1
        })).then(function (response) {
          let data = response.data;
          if (data.success) {
            return JDEventApplies.create({
              user_id: agency.id,
              jd_user: agency.jd_user,
              jd_pid: agency.jd_pid,
              goods_id: goods.skuId,

              urlAdvCode: data.urlAdvCode,
              shotCode: data.shotCode
            });
          } else {
            JDEventFails.create({
              user_id: agency.id,
              jd_user: agency.jd_user,
              jd_pid: agency.jd_pid,
              goods_id: goods.skuId
            });
          }
        });
      });
    });
  }

  return {
    applyCampaign: applyCampaign,

    getShareUrl: getShareUrl,
    getShareText: getShareText,
    getBuyKouling: getBuyKouling,
    handleShare: handleShare,

    getGoodsByAuctionId: getGoodsByAuctionId,
    getGoodsByUrl: getGoodsByUrl,

    priceTrend: priceTrend,

    getUserFanli: getUserFanli,
    getAgencyIncome: getAgencyIncome,

    alimamaSearch: alimamaSearch,
    alimamaAdzones: alimamaAdzones,
    alimamaAdzoneCreate: alimamaAdzoneCreate,

    getShortUrl: getShortUrl,

    getJdGoodsById: getJdGoodsById,
    jdApplyEvent: jdApplyEvent
  };
};
